<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="协议编码" prop="agreementCode">
        <el-input
          v-model="queryParams.agreementCode"
          placeholder="请输入协议编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="协议类型" prop="agreementType">
        <el-select
          v-model="queryParams.agreementType"
          placeholder="请选择协议类型"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in protocol_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="agreementList"
      style="margin-top: 15px; height: 75%"
      @sort-change="handleSortChange"
    >
      <el-table-column label="协议编码" align="center" prop="agreementCode" sortable="custom" />
      <el-table-column label="协议类型" align="center" prop="agreementType" width="120">
        <template #default="scope">
          <dict-tag :options="protocol_type" :value="scope.row.agreementType" />
        </template>
      </el-table-column>
      <el-table-column label="协议状态" align="center" prop="agreementStatus" width="100">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.agreementStatus)">
            {{ scope.row.agreementStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="creationDate" width="180" sortable="custom">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 协议详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="600px">
      <el-form :model="detailForm" label-width="100px" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="协议编码">
              <el-input v-model="detailForm.agreementCode" />
            </el-form-item>
            <el-form-item label="协议类型">
              <el-input v-model="detailForm.agreementType" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="协议状态">
              <el-input v-model="detailForm.agreementStatus" />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-input v-model="detailForm.creationDate" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="协议内容">
          <el-input v-model="detailForm.agreementContent" type="textarea" :rows="4" readonly />
        </el-form-item>
        <el-divider>结算规则</el-divider>
        <el-table :data="detailForm.agreementRuleList" border>
          <el-table-column label="税率" prop="taxRate" align="center" width="100" />
          <el-table-column label="结算周期" prop="settlementCycle" align="center" width="120" />
          <el-table-column label="生效时间" prop="effectiveDate" align="center" width="180">
            <template #default="scope">
              {{ parseTime(scope.row.effectiveDate) }}
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { getPartnerCodeByUserName } from '@/api/settled/partner'
import { getAgreementByPartnerCode } from '@/api/settled/agreement.js'

const { proxy } = getCurrentInstance()
const { protocol_type } = proxy.useDict('protocol_type')

// 调试：检查协议类型字典
console.log('protocol_type:', protocol_type)

// 响应式数据
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const agreementList = ref([])
const detailOpen = ref(false)
const detailForm = ref({})
const detailTitle = ref('')
const username = ref('')
const partnerCode = ref('')

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  agreementCode: null,
  agreementType: null,
  partnerCode: null,
  orderByColumn: 'creationDate',
  isAsc: 'desc'
})

// 初始化
onMounted(() => {
  console.log('Component mounted') // 调试：检查组件是否加载
  initial()
})

async function initial() {
  username.value = useUserStore().userInfo?.name || useUserStore().name
  console.log('username:', username.value) // 调试：检查用户名

  if (!username.value) {
    proxy.$modal.msgError('用户名不能为空')
    return
  }

  try {
    const response = await getPartnerCodeByUserName(username.value)
    console.log('Partner Code Response:', response) // 调试：检查 API 响应

    if (response.code === 200) {
      partnerCode.value = response.msg
      queryParams.partnerCode = partnerCode.value
      getList()
    } else {
      proxy.$modal.msgError(response.msg || '获取合作方编码失败')
    }
  } catch (error) {
    console.error('获取合作方编码失败:', error)
    proxy.$modal.msgError('获取合作方编码失败')
  }
}

// 获取协议列表
async function getList() {
  if (!queryParams.partnerCode) {
    proxy.$modal.msgError('合作方编码不能为空')
    return
  }

  loading.value = true
  try {
    const response = await getAgreementByPartnerCode(queryParams.partnerCode)
    console.log('Agreement List Response:', response) // 调试：检查 API 响应

    const data = response.data || response
    agreementList.value = data.rows ?? [data]
    total.value = data.total ?? agreementList.value.length
  } catch (error) {
    console.error('请求失败详情:', error)
    proxy.$modal.msgError('数据获取失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 排序变更
function handleSortChange({ prop, order }) {
  if (prop && order) {
    queryParams.orderByColumn = prop
    queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
    getList()
  }
}

// 查看详情
function handleDetail(row) {
  detailForm.value = { ...row }
  detailTitle.value = `协议详情 - ${row.agreementCode}`
  detailOpen.value = true
}

// 状态标签样式
function statusTagType(status) {
  return STATUS_TAG_MAP[status] || 'info'
}

// 时间格式化
function parseTime(time, format = '{y}-{m}-{d} {h}:{i}') {
  if (!time) return ''
  const date = new Date(time)
  if (isNaN(date.getTime())) return ''

  return format
    .replace('{y}', date.getFullYear())
    .replace('{m}', String(date.getMonth() + 1).padStart(2, '0'))
    .replace('{d}', String(date.getDate()).padStart(2, '0'))
    .replace('{h}', String(date.getHours()).padStart(2, '0'))
    .replace('{i}', String(date.getMinutes()).padStart(2, '0'))
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
</script>

<style scoped>
.agreement-table {
  margin-top: 15px;
  height: calc(100vh - 280px);
}
:deep(.el-table__body) td {
  padding: 8px 0;
}
.detail-content {
  white-space: pre-wrap;
  line-height: 1.6;
}
</style>